const axios = require('axios');
const { weatherConfig } = require('../config/weather.config');

class WeatherService {
  constructor() {
    this.baseURL = process.env.AMAP_WEATHER_URL || 'https://restapi.amap.com/v3/weather/weatherInfo';
    this.apiKey = process.env.AMAP_API_KEY;
    
    if (!this.apiKey) {
      console.warn('警告: 未配置高德地图API密钥');
    }
  }

  async getRegionalWeather(region) {
    try {
      console.log('正在请求天气数据:', region);
      console.log('使用的API地址:', this.baseURL);
      console.log('使用的API密钥:', this.apiKey ? '已配置' : '未配置');

      // 如果没有API密钥，返回模拟数据
      if (!this.apiKey) {
        console.log('使用模拟数据');
        return this.getMockData(region);
      }

      const response = await axios.get(this.baseURL, {
        params: {
          key: this.apiKey,
          city: region,
          extensions: 'base'
        }
      });

      console.log('API返回数据:', response.data);

      if (response.data.status !== '1') {
        throw new Error(`API返回错误: ${response.data.info}`);
      }

      return this.formatWeatherData(response.data);
    } catch (error) {
      console.error('天气服务异常:', error.message);
      if (error.response) {
        console.error('API响应详情:', error.response.data);
      }
      throw error;
    }
  }

  async getWeatherForecast(region) {
    try {
      console.log('正在请求天气预报数据:', region);

      // 如果没有API密钥，返回模拟数据
      if (!this.apiKey) {
        console.log('使用模拟预报数据');
        return this.getMockForecastData(region);
      }

      const response = await axios.get(this.baseURL, {
        params: {
          key: this.apiKey,
          city: region,
          extensions: 'all',  // 获取预报数据
          output: 'JSON'
        }
      });

      console.log('API返回预报数据:', response.data);

      if (response.data.status !== '1') {
        throw new Error(`API返回错误: ${response.data.info}`);
      }

      // 直接返回API提供的预报数据
      return this.formatForecastData(response.data);

    } catch (error) {
      console.error('天气预报服务异常:', error.message);
      if (error.response) {
        console.error('API响应详情:', error.response.data);
      }
      throw error;
    }
  }

  formatWeatherData(data) {
    if (!data.lives || data.lives.length === 0) {
      throw new Error('未找到天气信息');
    }

    const weather = data.lives[0];
    const formattedData = {
      region: weather.city,
      current: {
        temp: parseFloat(weather.temperature),
        condition: weather.weather,
        humidity: parseFloat(weather.humidity),
        windSpeed: `${weather.winddirection} ${weather.windpower}级`
      }
    };

    console.log('格式化后的天气数据:', formattedData);
    return formattedData;
  }

  formatForecastData(data) {
    if (!data.forecasts || data.forecasts.length === 0) {
      throw new Error('未找到天气预报信息');
    }

    const forecast = data.forecasts[0];
    return forecast.casts.map(day => ({
      date: day.date,
      dayWeather: day.dayweather,
      nightWeather: day.nightweather,
      dayTemp: day.daytemp,
      nightTemp: day.nighttemp,
      dayWind: day.daywind,
      nightWind: day.nightwind,
      dayPower: day.daypower,
      nightPower: day.nightpower
    }));
  }

  getMockForecastData(region) {
    const today = new Date();
    return Array.from({ length: 5 }, (_, i) => {
      const date = new Date(today);
      date.setDate(date.getDate() + i);
      return {
        date: date.toISOString().split('T')[0],
        dayWeather: '多云',
        nightWeather: '阴',
        dayTemp: '25',
        nightTemp: '18',
        dayWind: '东北',
        nightWind: '东北',
        dayPower: '3',
        nightPower: '3'
      };
    });
  }

  getMockData(region) {
    const mockData = {
      region: region,
      current: {
        temp: 21,
        condition: '多云',
        humidity: 65,
        windSpeed: '东北风 3级'
      }
    };
    console.log('返回模拟数据:', mockData);
    return mockData;
  }

  async getLifeIndex(region) {
    try {
      console.log('正在请求生活指数数据:', region);

      // 如果没有API密钥，返回模拟数据
      if (!this.apiKey) {
        console.log('使用模拟生活指数数据');
        return this.getMockLifeIndexData(region);
      }

      // TODO: 实现实际的生活指数API调用
      // 由于高德地图API不直接提供生活指数，这里暂时使用模拟数据
      return this.getMockLifeIndexData(region);

    } catch (error) {
      console.error('生活指数服务异常:', error.message);
      if (error.response) {
        console.error('API响应详情:', error.response.data);
      }
      throw error;
    }
  }

  getMockLifeIndexData(region) {
    return [
      {
        type: 'comfort',
        name: '舒适度',
        value: '较舒适'
      },
      {
        type: 'sport',
        name: '运动指数',
        value: '适宜'
      },
      {
        type: 'carWash',
        name: '洗车指数',
        value: '较适宜'
      },
      {
        type: 'uv',
        name: '紫外线指数',
        value: '中等'
      },
      {
        type: 'dressing',
        name: '穿衣指数',
        value: '热'
      },
      {
        type: 'fishing',
        name: '钓鱼指数',
        value: '较适宜'
      }
    ];
  }
}

module.exports = new WeatherService();